// tb_mqtt_client.c
#include "tb_mqtt_client.h"
#include <string.h>

static const char *TAG = "TB_MQTT";
static esp_mqtt_client_handle_t tb_client = NULL;
static bool tb_connected = false;
static mqtt_event_handler_t customer_mqtt_event_cp = NULL;

static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data) {
    esp_mqtt_event_handle_t event = event_data;
    if (customer_mqtt_event_cp != NULL)
    {
        customer_mqtt_event_cp(event);
    }
    switch ((esp_mqtt_event_id_t)event_id) {
        case MQTT_EVENT_CONNECTED:
            ESP_LOGI(TAG, "MQTT Connected");
            tb_connected = true;
            tb_rpc_init(tb_client);
            break;
        case MQTT_EVENT_DISCONNECTED:
            ESP_LOGW(TAG, "MQTT Disconnected");
            tb_connected = false;
            break;
        case MQTT_EVENT_ERROR:
            ESP_LOGE(TAG, "MQTT Error");
            break;
        case MQTT_EVENT_DATA:
            // 处理RPC订阅请求
            tb_handle_rpc(event->topic,(uint8_t *)event->data,event->data_len);
            break;
        default:
            break;
    }    
}

void tb_mqtt_start(const char *uri, const char *token,mqtt_event_handler_t customer_mqtt_event) {
    esp_mqtt_client_config_t mqtt_cfg = {
        .broker.address.uri = uri,
        .broker.address.port = 1883,
        .credentials.username = token
    };
    customer_mqtt_event_cp = customer_mqtt_event;
    ESP_LOGI(TAG, "Connecting to ThingsBoard: URI=%s, Token=%s", uri, token);

    tb_client = esp_mqtt_client_init(&mqtt_cfg);
    esp_mqtt_client_register_event(tb_client, ESP_EVENT_ANY_ID, mqtt_event_handler, NULL);
    esp_mqtt_client_start(tb_client);
}

bool tb_is_connected(void) {
    return tb_connected;
}

bool tb_send_telemetry(const char *json_payload) {
    if (!tb_is_connected()) {
        ESP_LOGW(TAG, "MQTT not connected. Skipping telemetry");
        return false;
    }

    int msg_id = esp_mqtt_client_publish(tb_client, "v1/devices/me/telemetry", json_payload, 0, 1, 0);
    if (msg_id < 0) {
        ESP_LOGE(TAG, "Failed to send telemetry");
        return false;
    }

    ESP_LOGI(TAG, "Telemetry sent: %s", json_payload);
    
    return true;
}

esp_mqtt_client_handle_t tb_get_client() {
    return tb_client;
}